package demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Javen
 */
@Slf4j
public class ProductConsumer {
    private int number = 0;
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();
        try {
            // 判断
            while (number != 0) {
                // 等待
                condition.await();
            }
            // 操作
            number++;
            log.info(" {} number: {} ", Thread.currentThread().getName(), number);
            // 通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            // 判断
            while (number != 1) {
                // 等待
                condition.await();
            }
            // 操作
            number--;
            log.info(" {} number: {} ", Thread.currentThread().getName(), number);
            // 通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final ProductConsumer prodConsumer = new ProductConsumer();

        new Thread(() -> {
            for (int i = 0; i < 6; i++) {
                prodConsumer.increment();
            }
        }, "T1").start();

        new Thread(() -> {
            for (int i = 0; i < 6; i++) {
                prodConsumer.decrement();
            }
        }, "T2").start();
    }
}
